AddCSLuaFile("cl_init.lua");
AddCSLuaFile("shared.lua");
include("shared.lua");

ENT.HitSound = Sound("stargateww/stunhit1.mp3");

local meta = FindMetaTable( "Player" )

function ENT:Initialize()
	self.BaseClass.Initialize(self);
	self.Radius = 100
	self.Damage = 0
	self.MaxPasses = 5
	if(self.Phys and self.Phys:IsValid()) then
		self.Phys:SetMass(40);
	end
end

function meta:Ragdoll()
	
	if !self:IsPlayer() and !self:IsValid() then return false end
	
	if !self:Alive() then return false end
	
	if self:InVehicle() then self:ExitVehicle() end
	
	self.IsStunned = true
	

	local ragdoll = ents.Create("prop_ragdoll")
	self.pos = self:GetPos()
	self.model = self:GetModel()
	self.angle = self:GetAngles()
	
	ragdoll:SetPos(self.pos)
	ragdoll:SetModel(self.model)
	ragdoll:SetAngles(self.angle)
	ragdoll:Spawn()
	
	local bones = ragdoll:GetPhysicsObjectCount()
	local veloc = self:GetVelocity()
	
	for i=0, bones-1 do
		ragdoll:GetPhysicsObjectNum(i):SetVelocity(veloc)
		ragdoll:GetPhysicsObjectNum(i):AddAngleVelocity(Vector( math.random(-1000,1000), math.random(-1000,1000), math.random(-1000,1000)))
	end
	
	self.weps = {}
	
	for k,v in pairs(self:GetWeapons()) do
		table.insert(self.weps, v:GetClass())
	end
	
	self:StripWeapons()
	self:Spectate(OBS_MODE_CHASE)
	self:SpectateEntity(ragdoll)
	self:SetNoTarget(true)
	
	self:StoreVariables(self.pos, self.model, self.angle, self.weps, ragdoll)

end

function meta:StoreVariables(pos, model, angles, weps, ragdoll)

	self.Pos = pos
	self.ModelP = model
	self.Angles = angles
	self.Weapons = weps
	self.Rag = ragdoll
	
end

function meta:RemoveVariables()

	self.Pos = nil
	self.ModelP = nil
	self.Angles = nil
	self.Weapons = nil
	self.Rag = nil
	
end

function meta:UnRagdoll()

	self:Spawn()
	self:SetPos(self.Pos)
	self:SetModel(self.ModelP)
	self:SetAngles(self.Angles)
	
	for k,v in pairs(self.Weapons) do
		self:Give(tostring(v))
	end
	
	self:SetNoTarget(false)
	
	self.Rag:Remove()
	
	self.IsStunned = false
	
	self:RemoveVariables()
	
end

function ENT:Blast(...)
	--self.BaseClass.Blast(self,...);
	WorldSound(self.HitSound,self.Entity:GetPos(),80,math.random(80,120));
	
	entsround = ents.FindInSphere(self.Entity:GetPos(), self.Radius)
	
		for k,v in pairs(entsround) do
			
			if not v:IsPlayer() then return end
			
			v:TakeDamage( self.Damage, self )
			
			local mathrand = math.random( 1, 5 )
			
			if mathrand == 5 then
				
				v:Ragdoll()
				
				timer.Create( "ragremove"..v:EntIndex(), math.random( 5, 10 ), 1, function() v:UnRagdoll() end )
				
			end
			
		end
end
